package com.bnq.logc.manager

import android.os.Handler
import android.os.Looper
import java.util.concurrent.*

object ExecutorManager {

    val ioExecutor:ExecutorService
    val scheduleExecutor:ScheduledExecutorService
    val netExecutor:ExecutorService
    val mainExecutor:Executor

    init {

        ioExecutor = ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            LinkedBlockingDeque(400),{ r ->
                Thread(
                    Thread.currentThread().threadGroup, r,
                    "logc-thread-write-log", 0
                ).apply {
                    if (isDaemon) {
                        isDaemon = false
                    }
                    if (priority != Thread.NORM_PRIORITY) {
                        priority = Thread.NORM_PRIORITY
                    }
                }
            }, ThreadPoolExecutor.DiscardPolicy()
        )

        netExecutor = ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            LinkedBlockingDeque(400),{ r ->
                Thread(
                    Thread.currentThread().threadGroup, r,
                    "logc-thread-net-log", 0
                ).apply {
                    if (isDaemon) {
                        isDaemon = false
                    }
                    if (priority != Thread.NORM_PRIORITY) {
                        priority = Thread.NORM_PRIORITY
                    }
                }
            }, ThreadPoolExecutor.DiscardPolicy()
        )
        scheduleExecutor = Executors.newSingleThreadScheduledExecutor { r ->
            Thread(
                Thread.currentThread().threadGroup, r,
                "logc-thread-schedule-log", 0
            ).apply {
                if (isDaemon) {
                    isDaemon = false
                }
                if (priority != Thread.NORM_PRIORITY) {
                    priority = Thread.NORM_PRIORITY
                }
            }
        }

        mainExecutor = object :Executor{

            private val handler = Handler(Looper.getMainLooper())

            override fun execute(command: Runnable) {
                handler.post(command)
            }

        }
    }
}